<?php

use Biz\service\bizActivity\mjLottery;

class LotteryAction extends ActionPlugin
{

    const USER_LEVEL = self::LEVEL_NOTHING;

    public function main()
    {
        $platform = $this->getPost('platform', mjLottery::ACTIVITY_PLATFORM_DEFAULT);

        $uid = 0;

        $third_id = '';

        $did = '';

        if ($platform == mjLottery::ACTIVITY_PLATFORM_WECHAT) {
            $third_id = $_COOKIE['openid'] ?? null;
            if (!$third_id) {
                throw new \Exception('微信未授权登录', 2);
            }
        } else {
            $uid = $this->uid;
            if (!$uid) {
                throw new \Exception('未登录', 2);
            }
            $did = $this->did;
        }

        $uip = self::getClientIp();

        $lottery = new mjLottery($uid, $did, $uip, $platform, $third_id);

        $lotteryResult = $lottery->lottery();

        $this->setSuccess($lotteryResult);
    }


    private static function getClientIp()
    {
        if (getenv('HTTP_CLIENT_IP')) {
            $clientIp = getenv('HTTP_CLIENT_IP');
        } else {
            if (getenv('HTTP_X_FORWARDED_FOR')) {
                $clientIp = getenv('HTTP_X_FORWARDED_FOR');
            } else {
                $clientIp = $_SERVER['REMOTE_ADDR'];
            }
        }
        return explode(',', $clientIp)[0];
    }
}